//
//  CategoryEventView.m
//  eticket
//
//  Created by AnhQuocNguyen on 4/14/13.
//  Copyright (c) 2013 SoinMedia. All rights reserved.
//

#import "CategoryEventView.h"

@implementation CategoryEventView

- (void)dealloc{
    SAFE_RELEASE_OBJECT(_tblView);
    SAFE_RELEASE_OBJECT(_arrayListData);
    SAFE_RELEASE_OBJECT(refeshHeaderTableView);
    SAFE_RELEASE_OBJECT(mHud);
    [super dealloc];
}
- (id)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        
        
    }
    return self;
}
- (void)setupUI{
    
    ////////////////////////////////////////////////////////////////////////////
    //Setup tableView
    if (!_tblView) {
        _tblView = [[UITableView alloc] initWithFrame:CGRectMake(0, 50, self.bounds.size.width, [Utilities isDeviceFourInches] ? self.bounds.size.height -  130 : self.bounds.size.height -  135)];
        _tblView.backgroundColor = [UIColor clearColor];
        _tblView.separatorStyle = UITableViewCellSelectionStyleNone;
        _tblView.delegate = self;
        _tblView.dataSource = self;
        [self addSubview:_tblView];
    }
    else{
        [_tblView reloadData];
    }
    
    ////////////////////////////////////////////////////////////////////////////
    //Pull to refresh
    if (refeshHeaderTableView == nil) {
        refeshHeaderTableView = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f - _tblView.bounds.size.height, self.frame.size.width, _tblView.bounds.size.height)];
        refeshHeaderTableView.delegate = self;
        [_tblView addSubview:refeshHeaderTableView];
        [refeshHeaderTableView setWhiteTextColor];
    }
    else{
        [self doneLoadingTableViewData];
    }
    
    
    
}
- (void)reloadData{
    mLoading = YES;
    [self initHUD:@"Loading...."];
    [mHud showWhileExecuting:@selector(waitting) onTarget:self withObject:nil animated:NO];
    
    
    self.backgroundColor = [UIColor clearColor];
    self.clipsToBounds = YES;
    self.layer.borderWidth = 1.;
    self.layer.cornerRadius = 2;
    self.layer.borderColor = [[UIColor colorWithRed:237/255 green:237/255 blue:237/255 alpha:.3] CGColor];
    [self getDataFromServer];

}


////////////////////////////////////////////////////////////////////////////////////////
//Post delegate de display MyTicket
#pragma mark - btnCategoryView_ChangeMyticket_Clicked
- (IBAction)btnCategoryView_ChangeMyticket_Clicked:(id)sender{
    if (![[NSUserDefaults standardUserDefaults] objectForKey:access_token_eTicket_userDefault] || [[[NSUserDefaults standardUserDefaults] objectForKey:access_token_eTicket_userDefault] isEqualToString:@""]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"You must be to login before view your ticket !!!" message:@"" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        SAFE_RELEASE_OBJECT(alert);
        return;
    }

    
    if ([_categoryEventViewDelegate respondsToSelector:@selector(categoryEventViewClickMyTicket:)]) {
        [_categoryEventViewDelegate categoryEventViewClickMyTicket:self];
    }
}


////////////////////////////////////////////////////////////////////////////////////////
#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
        if (buttonIndex == 0) {
            if ([_categoryEventViewDelegate respondsToSelector:@selector(categoryEventViewCancelRefeshData:)]) {
                [_categoryEventViewDelegate categoryEventViewCancelRefeshData:self];
            }
        }
        else{
            [self reloadData];
        }
}


////////////////////////////////////////////////////////////////////////////////////////
#pragma mark - cancelRequest
- (void)cancelRequest{
    [requestServer clearDelegatesAndCancel];
}
#pragma mark - get data froms server
- (void)getDataFromServer{
    dispatch_async(kBgQueue, ^{        
        NSString *urlString = [NSString stringWithFormat:@"%@%@%@", URL_island_API, categories_API, TOKEN__island];
        NSURL *url = [NSURL URLWithString:urlString];
         requestServer = [ASIFormDataRequest requestWithURL:url];
        [requestServer setTimeOutSeconds:20];
        [requestServer setCompletionBlock:^{
            
            NSError *error = nil;
            NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:[requestServer responseData] options:kNilOptions error:&error];
            
            /////////////////////////////////////////////////////////////////////
            //Set error server
            if (error) {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:[error description] delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Refesh", nil];
                [alert show];
                SAFE_RELEASE_OBJECT(alert);
                return;
            }
            
            
            /////////////////////////////////////////////////////////////////////
            //Set error json
            NSDictionary *jsonError = [jsonDic objectForKey:@"error"];
            if ([[jsonError objectForKey:@"code"] intValue] != 200) {
                NSArray *messageArray = [jsonError objectForKey:@"message"];
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:[messageArray objectAtIndex:0] delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Refesh", nil];
                [alert show];
                SAFE_RELEASE_OBJECT(alert);
                return;
            }
            
            ////////////////////////////////////////////////////////////////////
            //Set data
            NSDictionary *dicData = [jsonDic objectForKey:@"data"];
            SAFE_RELEASE_OBJECT(_arrayListData);
            _arrayListData = [[NSMutableArray alloc] init];
            
            NSArray *list = [dicData objectForKey: @"categories"];
            
            for (NSInteger i = 0 ; i < [list count]; i++) {
                NSDictionary *dicCate = [list objectAtIndex:i];
                CategoryEvent *categoryEvent = [[CategoryEvent alloc] init];
                categoryEvent.title = [dicCate objectForKey:@"title"];
                categoryEvent.idCategory = [dicCate objectForKey:@"id"];
                categoryEvent.slug_Category = [dicCate objectForKey:@"slug"];
                categoryEvent.thumbnail_Category = [dicCate objectForKey:@"thumbnail"];
                [_arrayListData addObject:categoryEvent];
                SAFE_RELEASE_OBJECT(categoryEvent);
            }
         
            //Setup tableView
            [self setupUI];
            mLoading = NO;
            
            
        }];
        
        
        [requestServer setFailedBlock:^{
            mLoading = NO;
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"Load category faild !!!" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Refesh", nil];
            alert.tag = ALERT_LISTEVENT_HOME;
            [alert show];
            SAFE_RELEASE_OBJECT(alert);
        }];
        
        
        [requestServer startSynchronous];
    });
}


////////////////////////////////////////////////////////////////////////////////////////
#pragma mark - UITableView Delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [_arrayListData count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 100;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellIdentifier = @"CategoryViewCell";
    CategoryViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"CategoryViewCell" owner:self options:nil];
        for (id curr in nib) {
            if ([curr isKindOfClass:[CategoryViewCell class]]) {
                cell = (CategoryViewCell *)curr;
                cell.exclusiveTouch = YES;
                break;
            }
        }
    }
    CategoryEvent *cate = [_arrayListData objectAtIndex:indexPath.row];
    cell.lbCategory.text = cate.title;
    
    NSString *urlString = [NSString stringWithFormat:@"%@%@",URL_island, cate.thumbnail_Category];
    NSURL *url = [NSURL URLWithString:urlString];
    [cell.imgViewAvatar setImageWithURL:url placeholderImage:[UIImage imageNamed:@"NoAvailable.jpeg"]];
    cell.imgViewAvatar.contentMode = UIViewContentModeScaleToFill;
    cell.imgViewAvatar.clipsToBounds = YES;
    [cell.parentViewCell setBackgroundColor:[UIColor grayColor]];
    cell.parentViewCell.alpha = 0.1;
    cell.parentViewCell.layer.cornerRadius = 2;
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    CategoryEvent *cate = [_arrayListData objectAtIndex:indexPath.row];
    NSString *urlString = [NSString stringWithFormat:@"%@%@%@/%@", URL_island_API,category_events_API, cate.idCategory, TOKEN__island];
    
    if (!_finalFindEvent) {
        POOL_START
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"FinalFindEventView" owner:self options:nil];
        _finalFindEvent = (FinalFindEventView *)[nib objectAtIndex:0];
        _finalFindEvent.frame = CGRectMake(330, [Utilities isDeviceFourInches] ? 38 : 43, 320, [UIScreen mainScreen].bounds.size.height - 43);
        [self.superview addSubview:_finalFindEvent];
        POOL_END
    }
    
     
    
    [UIView animateWithDuration:0.3 animations:^{
        
        CGRect frameTempCategory = self.frame;
        frameTempCategory.origin.x = - 320;
        self.frame = frameTempCategory;
        
        CGRect frametemp = _finalFindEvent.frame;
        frametemp.origin.x = 0;
        _finalFindEvent.frame = frametemp;
        
      
    } completion:^(BOOL finished) {
        self.hidden = YES;
        _finalFindEvent.urlString = urlString;
        _finalFindEvent.category = cate.title;
        [_finalFindEvent reloadData];
        _finalFindEvent.finalFindEventDelegate = self;
        if ([_categoryEventViewDelegate respondsToSelector:@selector(categoryEventView:didSelected:)]) {
            [_categoryEventViewDelegate categoryEventView:self didSelected:cate];
        }
    }];
}


////////////////////////////////////////////////////////////////////////////////////////
#pragma mark - FinalFindEvent Delegate
- (void)finalFindEventWithBack:(FinalFindEventView *)finalFindEvent{
    self.hidden = NO;
    [UIView animateWithDuration:0.3 animations:^{
        
        CGRect frameTempCategory = self.frame;
        frameTempCategory.origin.x = 0;
        self.frame = frameTempCategory;
        
        CGRect frametemp = _finalFindEvent.frame;
        frametemp.origin.x = 330;
        _finalFindEvent.frame = frametemp;
        
    } completion:^(BOOL finished) {
        _finalFindEvent.finalFindEventDelegate = nil;
        if ([_categoryEventViewDelegate respondsToSelector:@selector(categoryEventView:finalFindEventBack:)]) {
            [_categoryEventViewDelegate categoryEventView:self finalFindEventBack:_finalFindEvent];
        }
    }];
}




////////////////////////////////////////////////////////////////////////////////////////
#pragma mark - scrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
	[refeshHeaderTableView egoRefreshScrollViewDidScroll:scrollView];
    
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
	[refeshHeaderTableView egoRefreshScrollViewDidEndDragging:scrollView];
    
}

#pragma mark EGORefreshTableHeader Delegate
- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view{
    
    [self reloadTableViewDataSource];
	
    // send request to server
    [NSObject cancelPreviousPerformRequestsWithTarget:self
                                             selector:@selector(refreshTime)
                                               object:nil];
    
    addingDuration = 0;
    [self getDataFromServer];
}
-(void)refreshTime{
    addingDuration ++;
    
    [self performSelector:@selector(refreshTime) withObject:nil afterDelay:60.0];
    
}
- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view{
	NSLog(@"Data Source Last Updated");
	return [NSDate date];
	
}
- (void)reloadTableViewDataSource{
	NSLog(@"ReloadTable view source");
	_reloading = YES;
	
}
- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view{
	return _reloading; // should return if data source model is reloading
	
}
- (void)doneLoadingTableViewData{
	//  model should call this when its done loading
    NSLog(@"Done Loading Table View Data");
	_reloading = NO;
	[refeshHeaderTableView egoRefreshScrollViewDataSourceDidFinishedLoading:_tblView];
	
}



#pragma mark - MBProgressHUD
-(void)initHUD:(NSString *)alert {
    if (mHud) {
        [mHud removeFromSuperview];
        SAFE_RELEASE_OBJECT(mHud);
    }
    mHud = [[MBProgressHUD alloc] initWithView:self];
    //    mHud.delegate = self;
    mHud.labelText = alert;
    mHud.dimBackground = YES;
    [self addSubview:mHud];
    
}
-(void)waitting{
    while (mLoading) {
        usleep(5000);
    }
}

@end
